package com.teaboot.springbootsample.controller;

import com.teaboot.springbootsample.domain.Product;
import com.teaboot.springbootsample.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.DecimalMax;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class ProductController {

    @Autowired
    ProductService productService;

    @GetMapping("/product-list")
    public ModelAndView productList(){

        ModelAndView view = new ModelAndView("product-list");

        List<Product> list = productService.getProducts();

        view.addObject("productList", list);

        return view;
    }

    @GetMapping("/products-edit/{id}")
    public ModelAndView productEdit(@PathVariable Integer id){

        ModelAndView view = new ModelAndView("product-edit");

        Product product = productService.getProduct(id);

        view.addObject("product", product);

        return view;
    }

    @PostMapping("/products-add")
    public String addProduct(@RequestParam String name, @RequestParam BigDecimal price, @RequestParam String imgUrl){

        Product product = new Product();

        product.setName(name);
        product.setPrice(price);
        product.setImgUrl(imgUrl);

        productService.addProduct(product);

        return "redirect:/product-list";
    }


    @PostMapping("/products-update")
    public String updateProduct(@RequestParam Integer id, @RequestParam String name, @RequestParam BigDecimal price, @RequestParam String imgUrl){

        Product product = productService.getProduct(id);

        product.setName(name);
        product.setPrice(price);
        product.setImgUrl(imgUrl);

        productService.updateProduct(product);

        return "redirect:/product-list";
    }

    @PostMapping("/products-del")
    public String deleteProduct(@RequestParam Integer id){

        productService.deleteProduct(id);

        return "redirect:/product-list";
    }

}
